package org.blackjuly.sign.data;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.blackjuly.sign.util.IOUtil;

public class SystemDataSource {
	private static SystemDataSource instance = new SystemDataSource();
	private String driverClassName;
	private String url;
	private String username;
	private String password;
	
	private SystemDataSource() {
		InputStream is = SystemDataSource.class.getResourceAsStream("/application.properties");
		Properties prop = new Properties();
		try {
			prop.load(is);
			driverClassName = prop.getProperty("datasource.driverClassName");
			url = prop.getProperty("datasource.url");
			username = prop.getProperty("datasource.username");
			password = prop.getProperty("datasource.password");
			Class.forName(driverClassName);
		} catch (IOException e) {
			throw new RuntimeException("读取application.properties文件出错", e);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("[" + driverClassName +"]驱动读取错误", e);
		} finally {
			IOUtil.close(is);
		}
	}
	
	public static SystemDataSource getInstance() {
		return instance;
	}
	
	public Connection getConnection() throws SQLException {
		Connection conn = DriverManager.getConnection(url, username, password);
		return conn;
	}
	
	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void commit(Connection conn) {
		if (conn != null) {
			try {
				conn.commit();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}